<template>
  <div class="inline">
    <!-- 触发按钮 -->
    <el-button type="primary" @click="openDialog(false)">新增</el-button>

    <el-dialog
      v-model="visible"
      width="60%"
      class="dlg-fixed-footer"
      :title="creatingSystem ? '创建系统' : '系统/设备新增（一次创建多层设备）'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <!-- 顶部：起始父节点（仅系统层） + 创建系统按钮 --> 

      <el-form-item class="mb12">
        
        <el-button
          class="ml12"
          :type="mode === 'system' ? 'primary' : 'default'"
          :plain="mode !== 'system'"
          @click="switchMode('system')"
        >
          创建系统
        </el-button>

        <el-button
          class="ml12"
          :type="mode === 'device' ? 'primary' : 'default'"
          :plain="mode !== 'device'"
          @click="switchMode('device')"
        >
          创建母设备
        </el-button>

        <el-button
          class="ml12"
          :type="mode === 'anyDevice' ? 'primary' : 'default'"
          :plain="mode !== 'anyDevice'"
          @click="switchMode('anyDevice')"
        >
          自由创建设备
        </el-button>

        <!-- 顶部说明：按当前模式展示 -->
        <div class="tip mt8" v-if="mode === 'device'">
          选择 “系统” 添加母设备。
        </div>
        <div class="tip mt8" v-else-if="mode === 'anyDevice'">
          从任意节点添加设备。
        </div>




        

        <!-- <el-button
          v-if="mode === 'device'"
          class="ml12"
          type="warning"
          @click="toggleShowAllNodes"
        >
          {{ showAllNodes ? "切换至系统" : "切换至自定义设备层级节点" }}
        </el-button>

        <div class="tip mt8" v-if="mode === 'device'">
          {{
            showAllNodes
              ? "切换至 “系统”，选择 “系统” 添加母设备。"
              : "选择 “自定义设备层级节点” 可从任意节点添加设备。"
          }}
        </div> -->
      </el-form-item>

      <el-form v-if="mode === 'device' || mode === 'anyDevice'" :label-width="parentFormLabelWidth" class="mb12">
  <el-form-item :label="parentLabel">
    <div class="flex-row">
      <el-cascader
        :key="cascaderKey"
        ref="cascaderRef"
        v-model="rootPath"
        :props="cProps"
        clearable
        filterable
        :placeholder="mode==='device' ? '请选择系统' : '请选择父节点'"
        style="min-width: 360px"
        show-all-levels
        @change="onRootChange"
      >
        <template #default="{ node, data }">
          <div class="cas-opt">
            <span class="cas-label" :title="data.label">{{ data.label }}</span>
            <el-tag
              v-if="typeLabelOf(node, data)"
              size="small"
              :type="typeTagType(typeLabelOf(node, data))"
              effect="light"
              class="cas-badge"
            >
              {{ typeLabelOf(node, data) }}
            </el-tag>
          </div>
        </template>
      </el-cascader>
    </div>
  </el-form-item>
</el-form>

      <!-- 设备层卡片 -->
      <div class="cards">
        <el-card
          v-for="(item, i) in layers"
          :key="item.uid"
          shadow="hover"
          class="layer-card"
        >
          <template #header>
            <div class="card-head">
              <div class="title">
                <!-- <el-tag type="info" round size="small">
                  第 {{ i + 1 }} 层（预估层级：{{ baseLevel + i + 1 }}）
                </el-tag> -->
                <!-- <span class="sep">|</span> -->
                <el-tag size="small" type="primary" effect="plain">
                  {{ typeName(item.nodeType) }}
                </el-tag>
                <!-- <span class="sep">|</span> -->
                <span class="path-preview">{{ pathPreview(i) }}</span>
              </div>
              <div class="ops" v-if="!creatingSystem">
                <!-- <el-button link size="small" :disabled="i === 0" @click="moveUp(i)">上移</el-button>
                <el-button link size="small" :disabled="i === layers.length - 1" @click="moveDown(i)">下移</el-button>
                <el-button link size="small" @click="dup(i)">复制</el-button>
                <el-button link size="small" @click="insertAfter(i)">下方插入</el-button> -->
                <el-button
                  link
                  size="small"
                  type="danger"
                  :disabled="layers.length === 1"
                  @click="remove(i)"
                  >删除</el-button
                >
              </div>
            </div>
          </template>

          <el-form
            :model="item"
            :rules="rules"
            :ref="setFormRef(i)"
            label-width="92px"
            class="layer-form"
          >
            <el-row :gutter="12">
              <el-col :span="8">
                <!-- 唯一的“设备类型”表单项 -->
                <el-form-item label="设备类型" prop="nodeType">
                  <el-select-v2
                    v-model="item.nodeType"
                    :options="typeOptionsFor(i)"
                    :disabled="creatingSystem"
                    placeholder="请选择类型"
                    clearable
                    filterable
                    @change="onTypeChange(i)"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="设备编码" prop="code">
                  <el-input
                    v-model="item.code"
                    placeholder="设备编码（唯一，必填, 大写字母）"
                    @input="onCodeInput(item, $event)"
                    inputmode="latin"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备名称" prop="name">
                  <el-input v-model="item.name" placeholder="请输入名称" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="12">
              <el-col :span="8">
                <el-form-item label="归属部门" prop="deptId">
                  <el-tree-select
                    v-model="item.deptId"
                    :data="deptOptions"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children',
                    }"
                    value-key="id"
                    placeholder="请选择归属部门"
                    check-strictly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备类别">
                  <el-input v-model="item.beType" placeholder="" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备模块">
                  <el-input v-model="item.mokuai" placeholder="" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="12">
              <el-col :span="8">
                <el-form-item label="设备区域">
                  <el-input v-model="item.area" placeholder="" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备规格">
                  <el-input v-model="item.specification" placeholder="" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备材质">
                  <el-input v-model="item.material" placeholder="" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="12">
              <el-col :span="8">
                <el-form-item label="设备单位">
                  <el-input v-model="item.unit" placeholder="例：台" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备数量">
                  <el-input v-model="item.quantity" placeholder="" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备金额">
                  <el-input
                    v-model="item.amount"
                    placeholder="填数值即可 (单位:万 )"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="12">
              <el-col :span="8">
                <el-form-item label="设计温度">
                  <el-input v-model="item.designTemp" placeholder="(单位:℃ )" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设计压力">
                  <el-input
                    v-model="item.designPress"
                    placeholder="(单位:MPa )"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="电机功率">
                  <el-input
                    v-model="item.motorPower"
                    placeholder="填数值即可 (单位:KW )"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="12">
              <el-col :span="8">
                <el-form-item label="搅拌形式">
                  <el-input v-model="item.mixingType" placeholder="" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="特种设备">
                  <el-select
                    v-model.number="item.isSpecial"
                    placeholder="请选择类型"
                  >
                    <el-option label="是" :value="1" />
                    <el-option label="否" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备状态" prop="status">
                  <el-select
                    v-model.number="item.status"
                    placeholder="请选择设备状态"
                  >
                    <el-option
                      v-for="dict in asset_node_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="Number(dict.value)"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="12">
              <el-col :span="8">
                <el-form-item label="设备型号">
                  <el-input v-model="item.model" placeholder="" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="设备品牌">
                  <el-input v-model="item.brand" placeholder="" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="制造厂家">
                  <el-input v-model="item.manufacturer" placeholder="" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="备注说明">
              <el-input
                v-model="item.remark"
                placeholder="可空"
                type="textarea"
                :rows="2"
              />
            </el-form-item>

            <el-row :gutter="12">
              <el-col :span="24">
                <el-divider content-position="left">备件信息</el-divider>

                <div class="spare-scroll">
                  <!-- 表头 -->
                  <div class="spare-table-header">
                    <div class="col col-name">备件名称</div>
                    <div class="col col-vendor">厂商 (vendor)</div>
                    <div class="col col-spec">规格 (spec)</div>
                    <!-- <div class="col col-status">状态</div> -->
                    <div class="col col-ops">操作</div>
                  </div>

                  <!-- 每行 -->
                  <div
                    v-for="(sr, j) in item.spareRelations"
                    :key="sr.uid"
                    class="spare-table-row"
                  >
                    <!-- 备件名称 -->
                    <div class="col col-name">
                      <el-select-v2
                        v-model="sr.spareId"
                        :options="spareListOptions"
                        placeholder="请选择备件"
                        filterable
                        clearable
                        style="width: 100%"
                        @change="onSpareChange(i, j)"
                      />
                    </div>

                    <!-- 厂商 -->
                    <div class="col col-vendor">
                      <el-select-v2
                        v-model="sr.vendor"
                        :options="sr.vendorOptions"
                        placeholder="请选择厂商"
                        filterable
                        clearable
                        style="width: 100%"
                        :disabled="!sr.spareId"
                        @change="onVendorChange(i, j)"
                      />
                    </div>

                    <!-- 规格 -->
                    <div class="col col-spec">
                      <el-select-v2
                        v-model="sr.spec"
                        :options="sr.specOptions"
                        placeholder="请选择规格"
                        filterable
                        clearable
                        style="width: 100%"
                        :disabled="!sr.vendor"
                      />
                    </div>

                    <!-- 状态 -->
                    <!-- <div class="col col-status">
    <el-select v-model="sr.status" placeholder="状态" style="width: 100%">
      <el-option label="启用" :value="1" />
      <el-option label="停用" :value="0" />
    </el-select>
  </div> -->

                    <!-- 操作 -->
                    <div class="col col-ops flex-center">
                      <el-button
                        link
                        size="small"
                        type="primary"
                        @click="copySpareRelation(i, j)"
                        >复制</el-button
                      >
                      <el-button
                        link
                        size="small"
                        type="danger"
                        @click="removeSpareRelation(i, j)"
                        >删除</el-button
                      >
                    </div>
                  </div>
                </div>
                <!-- 新增按钮 -->
                <div class="add-spare-btn">
                  <el-button
                    size="small"
                    type="success"
                    plain
                    @click="addSpareRelation(i)"
                  >
                    ＋ 新增备件组
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>

      <!-- 新增一层：创建系统模式隐藏 -->
      <div class="add-area" v-if="!creatingSystem && layers.length">
        <el-button @click="addTail">＋ 新增一层</el-button>
      </div>

      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submit"
          >创建</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  watch,
  computed,
  onMounted,
  getCurrentInstance,
  nextTick,
} from "vue"; // ← ✅ nextTick
import { ElMessage } from "element-plus";
import { cascaderChildren, createRoute } from "@/api/sbtz/sbtz";
import { loadAllParams } from "@/api/page";
import {
  listSpares,
  listSpare,
  getVendorsBySpare,
  getSpecsBySpareVendor,
} from "@/api/sbtz/spare";
import { listSbtype } from "@/api/sbtz/sbtype";
import { deptTreeSelect } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { asset_node_status } = proxy.useDict("asset_node_status");

const visible = ref(false);
const loading = ref(false);
const creatingSystem = ref(false); // true=创建系统；false=在系统下新增链路
const cascaderKey = ref(0);
const cascaderRef = ref(null);
const showAllNodes = ref(false);
const selectedParentType = ref(null);
const parentLabel = ref("系统");
const mode = ref("device");
  

// 顶部“父节点选择”这行的 label 宽度：device=90px，anyDevice=160px，其它(系统)为0避免占位
const parentFormLabelWidth = computed(() => {
  if (mode.value === 'device') return '60px';
  if (mode.value === 'anyDevice') return '160px';
  return '0px'; // 'system' 时这块本就不显示，给0更稳妥
});
 


// 起始父节点（仅系统层）
const rootPath = ref([]); // 只允许长度=1
const selectedParentId = computed(() => {
  if (Array.isArray(rootPath.value) && rootPath.value.length) {
    // 设备模式取系统（第一个）；任意设备模式取最后一个节点
    return mode.value === 'device'
      ? rootPath.value[0]
      : rootPath.value[rootPath.value.length - 1];
  }
  return 0;
});


// ✅ 新增：控制强制刷新

function refreshCascader() {
  // ✅ 新增：刷新起始父节点选择框数据
  // rootPath.value = [];               // 清空当前选择（可保留也行，看需求）
  cascaderKey.value += 1; // 变更 key，强制组件重建，触发懒加载
}

function hideAllCards() {
  layers.splice(0, layers.length);
}

async function focusCascader() {
  await nextTick();
  // 优先用组件的 focus（若支持），否则退回到原生 input
  if (cascaderRef.value?.focus) {
    cascaderRef.value.focus();
  } else {
    cascaderRef.value?.$el?.querySelector?.("input")?.focus();
  }
}

// 新增一条备件组
function addSpareRelation(layerIndex) {
  const layer = layers[layerIndex];
  layer.spareRelations.push({
    uid: Math.random().toString(36).slice(2),
    spareId: null,
    vendor: null,
    spec: null,
    vendorOptions: [],
    specOptions: [],
  });
}

function toggleShowAllNodes() {
  showAllNodes.value = !showAllNodes.value;

  // ✅ 同步更新标题文字
  parentLabel.value = showAllNodes.value ? "自定义设备层级节点" : "系统";

  refreshCascader();
  hideAllCards();
  // ElMessage.info(
  //   showAllNodes.value
  //     ? "自定义设备层级节点模式已开启，可选择任意节点"
  //     : "已切回仅系统层模式"
  // );
}

// 删除一条备件组
function removeSpareRelation(layerIndex, relationIndex) {
  layers[layerIndex].spareRelations.splice(relationIndex, 1);
}

// 复制一条备件组
function copySpareRelation(layerIndex, relationIndex) {
  const src = layers[layerIndex].spareRelations[relationIndex];
  layers[layerIndex].spareRelations.splice(relationIndex + 1, 0, {
    ...JSON.parse(JSON.stringify(src)),
    uid: Math.random().toString(36).slice(2),
  });
}

// 当选择备件变化时 -> 更新厂商
async function onSpareChange(layerIndex, relationIndex) {
  const sr = layers[layerIndex].spareRelations[relationIndex];
  sr.vendor = null;
  sr.spec = null;
  sr.specOptions = [];
  sr.vendorOptions = [];
  if (sr.spareId) sr.vendorOptions = await getVendorsBySpare(sr.spareId);
}

// 当选择厂商变化时 -> 更新规格
async function onVendorChange(layerIndex, relationIndex) {
  const sr = layers[layerIndex].spareRelations[relationIndex];
  sr.spec = null;
  sr.specOptions = [];
  if (sr.spareId && sr.vendor)
    sr.specOptions = await getSpecsBySpareVendor(sr.spareId, sr.vendor);
}

// 层级顺序常量
const ORDER = ["SYSTEM", "MACHINE", "MODULE", "COMPONENT", "PART"];
const TYPE_LABELS = {
  SYSTEM: "系统",
  MACHINE: "母设备",
  MODULE: "子设备",
  COMPONENT: "部件",
  PART: "零件",
};

// 估算层级（父路径长度 + 当前层序号）
const baseLevel = ref(0);
watch(rootPath, () => {
  baseLevel.value = creatingSystem.value ? 0 : rootPath.value?.length || 0;
});

// 只显示系统层：根请求返回系统列表，强制 leaf=true
function typeLabelOf(node, data) {
  const code = data && (data.nodeType || data.node_type);
  if (code && TYPE_LABELS[code]) return TYPE_LABELS[code];
  return null;
}
function typeTagType(label) {
  const map = {
    系统: "success",
    母设备: "primary",
    子设备: "warning",
    部件: "warning",
    零件: "info",
  };
  return map[label] || "info";
}
function typeName(code) {
  return TYPE_LABELS[code] || code || "未知";
}

// 懒加载：device=仅系统; anyDevice=全部
const cProps = {
  checkStrictly: true,
  emitPath: true,
  value: "id",
  label: "label",
  lazy: true,
  lazyLoad: async (node, resolve) => {
    const parentId = node.level === 0 ? 0 : node.value;
    try {
      const res = await cascaderChildren(parentId);
      let list = res?.data || [];

      if (mode.value === "device" && node.level === 0) {
        list = list
          .filter((x) => (x.nodeType || x.node_type) === "SYSTEM")
          .map((x) => ({ ...x, leaf: true }));
      }
      resolve(list);
    } catch {
      resolve([]);
    }
  },
};

function forceSingleMotherCard() {
  // 只保留一张“母设备”卡片
  layers.splice(0, layers.length, makeEmptyLayer("MACHINE"));
}

// 只保留“当前层及以下”的类型（把上层类型从当前层可选项中移除）
// 第 i 层允许的类型：ORDER.slice(1 + i)
function allowedTypeCodesForIndex(i) {
  if (creatingSystem.value) return ["SYSTEM"];
  const start = Math.min(1 + i, ORDER.length - 1); // 0层→从1开始(去掉SYSTEM)，1层→从2开始...
  return ORDER.slice(start);
}

// 供下拉使用的 options（结合后端字典）
const typeOptions = ref([]);
function typeOptionsFor(i) {
  if (creatingSystem.value) {
    // 创建系统模式：只显示 SYSTEM
    const sys = typeOptions.value.find((o) => o.value === "SYSTEM");
    return sys ? [sys] : [{ value: "SYSTEM", label: TYPE_LABELS.SYSTEM }];
  }
  const allowed = new Set(allowedTypeCodesForIndex(i));
  const filtered = typeOptions.value.filter((opt) => allowed.has(opt.value));
  if (!filtered.length) {
    // 兜底：即使后端没配齐字典，也给出期望类型
    const expect = ORDER[Math.min(1 + i, ORDER.length - 1)];
    return [{ value: expect, label: TYPE_LABELS[expect] || expect }];
  }
  return filtered;
}

// 字典与数据
const spareListOptions = ref([]);
const deptOptions = ref(undefined);
const deptMap = new Map();

function buildDeptTree(nodes = []) {
  return nodes.map((n) => {
    const children = buildDeptTree(n.children || []);
    const node = {
      ...n,
      children,
      // 规则：有 children 的视为目录/公司层，禁用选择；叶子可选
      disabled: children.length > 0,
    };
    deptMap.set(n.id, node);
    return node;
  });
}

function isLeafDeptId(id) {
  const node = deptMap.get(id);
  return !!node && (!node.children || node.children.length === 0);
}

function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptMap.clear();
    deptOptions.value = buildDeptTree(response.data || []);
  });
}

async function getTypeList() {
  const res = await listSbtype(loadAllParams);
  typeOptions.value = (res?.rows ?? []).map(
    ({ typeCode: value, displayName: label }) => ({ value, label })
  );
}
async function getSpareList() {
  // 你也可直接用 listSpares；这里沿用 listSpare 以匹配你现有 API
  const res = await listSpare(loadAllParams);
  spareListOptions.value = (res?.rows ?? []).map(
    ({ id: value, name: label }) => ({ value, label })
  );
}

onMounted(() => {
  getTypeList();
  getSpareList();
  getDeptTree();
});

// 层数据 + 规则
function makeEmptyLayer(type = "PART") {
  return {
    uid: Math.random().toString(36).slice(2),
    nodeType: type,
    name: "",
    code: "",
    stockTotal: 0,
    stockAvailable: 0,
    remark: "",
    specification: "",
    model: "",
    material: "",
    power: "",
    brand: "",
    manufacturer: "",
    isSpecial: null,
    deptId: null,
    status: 0,
    spareIds: [],
    spareRelations: [
      {
        uid: Math.random().toString(36).slice(2),
        spareId: null,
        vendor: null,
        spec: null,
        status: 1,
        vendorOptions: [],
        specOptions: [],
      },
    ],

    // 新增字段
    mokuai: null,
    area: null,
    designTemp: null,
    designPress: null,
    motorPower: null,
    mixingType: null,
    beType: null,
    unit: null,
    quantity: null,
    amount: null,
  };
}
const layers = reactive([]);
const formRefs = [];
const setFormRef = (i) => (el) => {
  formRefs[i] = el;
};

function onCodeInput(item, val) {
  const inputEl = event?.target || event?.srcElement || document.activeElement;
  if (!inputEl) {
    // 容错
    const s = (val || "").toUpperCase().replace(/[^A-Z0-9\-_]/g, "");
    if (s !== item.code) item.code = s;
    return;
  }

  // 记录光标位置
  const start = inputEl.selectionStart;
  const end = inputEl.selectionEnd;

  // 转换值
  const raw = val || "";
  const filtered = raw.toUpperCase().replace(/[^A-Z0-9\-_]/g, "");
  item.code = filtered;

  // 异步恢复光标位置（下一帧）
  requestAnimationFrame(() => {
    try {
      inputEl.setSelectionRange(start, end);
    } catch {}
  });
}
const rules = reactive({
  nodeType: [{ required: true, message: "请选择类型", trigger: "change" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入编号", trigger: "blur" }],
  deptId: [{ required: true, message: "请选择部门", trigger: "blur" }],
});

// 类型自动推进
function nextType(prev) {
  const idx = ORDER.indexOf(prev);
  if (idx < 0) return "PART";
  return ORDER[Math.min(idx + 1, ORDER.length - 1)];
}

// 路径预览
function pathPreview(i) {
  const parts = [];
  for (let k = 0; k <= i; k++) {
    const r = layers[k];
    if (!r?.name) continue;
    parts.push(r.code ? `${r.name}(${r.code})` : r.name);
  }
  return parts.join(" / ");
}

// 卡片操作
function addTail() {
  if (layers.length === 0) {
    if (creatingSystem.value) {
      return ElMessage.warning("创建系统模式下不支持新增下一层。");
    } else {
      if (!selectedParentId.value)
        return ElMessage.error("请先选择起始父节点。");
      const nextTypeMap = {
        SYSTEM: "MACHINE",
        MACHINE: "MODULE",
        MODULE: "COMPONENT",
        COMPONENT: "PART",
      };
      const firstType = nextTypeMap[selectedParentType.value] || "MACHINE";
      layers.push(makeEmptyLayer(firstType));
    }
    return;
  }
  if (creatingSystem.value) {
    return ElMessage.warning("创建系统模式下不支持新增下一层。");
  }
  const last = layers[layers.length - 1];
  layers.push(makeEmptyLayer(nextType(last.nodeType)));
}

function insertAfter(i) {
  if (creatingSystem.value) return;
  const src = layers[i];
  layers.splice(i + 1, 0, makeEmptyLayer(nextType(src.nodeType)));
}
function dup(i) {
  if (creatingSystem.value) return;
  const src = layers[i];
  layers.splice(i + 1, 0, {
    ...JSON.parse(JSON.stringify(src)),
    uid: Math.random().toString(36).slice(2),
  });
}
function remove(i) {
  if (creatingSystem.value) return; // 创建系统模式下不允许删唯一层
  if (layers.length > 1) layers.splice(i, 1);
}
function moveUp(i) {
  if (i > 0) {
    const t = layers[i - 1];
    layers[i - 1] = layers[i];
    layers[i] = t;
  }
}
function moveDown(i) {
  if (i < layers.length - 1) {
    const t = layers[i + 1];
    layers[i + 1] = layers[i];
    layers[i] = t;
  }
}

 

// 统一切换入口（不再有“切回系统”的toggle）
function switchMode(newMode) {
  mode.value = newMode;

  // 每次切换都清场
  rootPath.value = [];
  hideAllCards();
  refreshCascader();

  if (newMode === "system") {
    creatingSystem.value = true;
    showAllNodes.value = false;
    parentLabel.value = "系统";
    layers.splice(0, layers.length, makeEmptyLayer("SYSTEM"));
  } else if (newMode === "device") {
    creatingSystem.value = false;
    showAllNodes.value = false;      // 只选系统
    parentLabel.value = "系统";
  } else if (newMode === "anyDevice") {
    creatingSystem.value = false;
    showAllNodes.value = true;       // 强制任意节点
    parentLabel.value = "自定义设备层级节点";
  }
}



function switchToCreateSystem() {
  // 如果弹窗还没开，就沿用原逻辑开到“创建系统”模式
  if (!visible.value) return openDialog(true);

  // 已经在弹窗里：切换到“创建系统”模式
  creatingSystem.value = true; // 进入创建系统模式
  rootPath.value = []; // 清空父节点选择
  layers.splice(
    0,
    layers.length, // 只保留一张系统卡片
    makeEmptyLayer("SYSTEM")
  );
}

// 打开弹窗（两种模式）


// 打开弹窗：默认进入“创建母设备（系统）”选择
function openDialog(asCreateSystem) {
  visible.value = true;

  // 总是重置（防缓存）
  mode.value = "device";
  creatingSystem.value = !!asCreateSystem;
  showAllNodes.value = false;
  parentLabel.value = "系统";
  rootPath.value = [];
  hideAllCards();
  refreshCascader();

  if (creatingSystem.value) {
    layers.push(makeEmptyLayer("SYSTEM"));
  }
}


// 重置
function resetDialog() {
  rootPath.value = [];
  layers.splice(0, layers.length);
}

// 选择变更：只保留第一段（系统层）
// 选择父节点后再生成卡片
async function onRootChange(val) {
  if (!Array.isArray(val) || val.length === 0) {
    rootPath.value = [];
    hideAllCards();
    return;
  }

  if (mode.value === "device") {
    // 只允许系统
    if (val.length > 1) {
      rootPath.value = [val[0]];
      ElMessage.warning("起始父节点仅支持选择系统层，已自动纠正为系统。");
    }
  }

  // 取最后一个节点和类型
  const nodes = cascaderRef.value?.getCheckedNodes?.() || [];
  const node = nodes[0]?.data || {};
  const parentType = node.nodeType || node.node_type || "SYSTEM";

  const nextTypeMap = {
    SYSTEM: "MACHINE",
    MACHINE: "MODULE",
    MODULE: "COMPONENT",
    COMPONENT: "PART",
    PART: "PART",
  };
  const nextType = nextTypeMap[parentType] || "MACHINE";

  // 显示首张正确类型卡片
  layers.splice(0, layers.length, makeEmptyLayer(nextType));
}

function onTypeChange(i) {
  // 可选：当第 i 层类型变化时，自动把 i+1..末尾 的类型顺着链条重算
  for (let k = i + 1; k < layers.length; k++) {
    layers[k].nodeType = nextType(layers[k - 1].nodeType);
  }
}

// 提交
const emit = defineEmits(["refresh"]);
async function submit() {
  if (creatingSystem.value) {
    if (layers.length !== 1 || layers[0].nodeType !== "SYSTEM") {
      return ElMessage.error("创建系统模式仅支持创建单层系统。");
    }
  } else {
    if (!selectedParentId.value) {
      return ElMessage.error("请先选择起始父节点。");
    }
  }
  if (!layers.length) return ElMessage.error("请至少新增一层");

  for (let i = 0; i < layers.length; i++) {
    const x = layers[i];
    if (!x.nodeType || !x.name)
      return ElMessage.error(`第 ${i + 1} 层：类型、名称为必填`);
  }

  const startParentId = creatingSystem.value ? 0 : selectedParentId.value;
  // 在 submit() 里加：先校验每一层的 deptId 是否为叶子
  for (let i = 0; i < layers.length; i++) {
    const x = layers[i];
    if (x.deptId && !isLeafDeptId(x.deptId)) {
      return ElMessage.error(
        `第 ${i + 1} 层的“归属部门”必须选择具体部门（不能选目录/公司层）`
      );
    }
  }

  const payload = {
    startParentId,
    reuseCode: false,
    layers: layers.map((it) => ({
      nodeType: it.nodeType,
      name: it.name,
      code: it.code,
      spareIds: it.spareIds || [],
      spareRelations: it.spareRelations
        .filter((sr) => sr.spareId)
        .map((sr) => ({
          spareId: sr.spareId,
          vendor: sr.vendor,
          spec: sr.spec,
        })),
      remark: it.remark,
      specification: it.specification,
      model: it.model,
      material: it.material,
      power: it.power,
      brand: it.brand,
      manufacturer: it.manufacturer,
      isSpecial: it.isSpecial,
      deptId: it.deptId,
      status: it.status,

      // 新增字段
      mokuai: it.mokuai ?? null,
      area: it.area ?? null,
      designTemp: it.designTemp ?? null,
      designPress: it.designPress ?? null,
      motorPower: it.motorPower ?? null,
      mixingType: it.mixingType ?? null,
      beType: it.beType ?? null,
      unit: it.unit ?? null,
      quantity: it.quantity ?? null,
      amount: it.amount ?? null,
    })),
  };

  loading.value = true;
  try {
    const res = await createRoute(payload);
    if (res.code === 200) {
      if (creatingSystem.value) {
        // ✅ 创建系统成功：不关闭弹窗，刷新并聚焦父节点选择框
        ElMessage.success("系统创建成功");
        refreshCascader(); // 触发级联懒加载，拿到最新系统
        hideAllCards();
        creatingSystem.value = false; // 退出“创建系统”模式，便于选择父节点后走母设备流程
        await focusCascader(); // 鼠标焦点放到选择框
        return; // 不关闭弹窗
      }

      // ✅ 其他情况按原逻辑：关闭弹窗（如在已有系统下建链）
      ElMessage.success("新增成功");
      refreshCascader(); // 若你也想在建链成功后刷新下拉，保留这行
      emit("refresh", startParentId);
      visible.value = false;
    } else {
      ElMessage.error(res?.msg || "新增失败");
    }
  } catch (e) {
    ElMessage.error(e?.msg || "创建失败");
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.inline {
  display: inline-block;
}
.mb12 {
  margin-bottom: 12px;
}
.ml12 {
  margin-left: 12px;
}
.mt8 {
  margin-top: 8px;
}
.flex-row {
  display: flex;
  align-items: center;
}
.tip {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}

.cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.layer-card {
  border-radius: 12px;
}
.card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-head .title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}
.sep {
  color: #c0c4cc;
}
.path-preview {
  color: #909399;
}

.layer-form :deep(.el-input),
.layer-form :deep(.el-select),
.layer-form :deep(.el-input-number) {
  width: 100%;
}

.add-area {
  margin-top: 10px;
}

.cas-opt {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
}
.cas-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.cas-badge {
  flex: 0 0 auto;
}

/* 备件表格样式 */
.spare-table-header,
.spare-table-row {
  display: grid;
  grid-template-columns: 30% 30% 30% 10%;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding: 6px 10px;
}

.spare-table-header {
  background: #f5f7fa;
  font-weight: 500;
  color: #606266;
  border-top: 1px solid #ebeef5;
}

.spare-table-row {
  background: #fff;
}
.spare-table-row:nth-child(even) {
  background: #fafafa;
}

.col {
  padding: 4px 8px;
}

.col-ops {
  text-align: center;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.add-spare-btn {
  margin-top: 8px;
  text-align: right;
  margin-bottom: 10px;
}

/* ✅ 新增：滚动容器（只滚表体，保留表头吸顶） */
.spare-scroll {
  max-height: 45vh;
  overflow: auto;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background: #fff;
  /* 让“行”的上下留白不被裁掉 */
  padding: 0 6px 6px;
}

/* ✅ 让表头在容器里吸顶 */
.spare-table-header {
  position: sticky;
  top: 0;
  z-index: 1;
}

/* 保持你原有的网格列布局不变 */
.spare-table-header,
.spare-table-row {
  display: grid;
  grid-template-columns: 30% 30% 30% 10%;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding: 6px 10px;
}

.spare-table-header {
  background: #f5f7fa;
  font-weight: 500;
  color: #606266;
  border-top: 1px solid #ebeef5;
}

/* 让对话框整体按列布局，并限制高度 */
:deep(.dlg-fixed-footer .el-dialog) {
  display: flex;
  flex-direction: column;
  height: 80vh; /* 对话框总高度 */
  max-height: 90vh; /* 防止过高溢出屏幕 */
}

/* 头部加一条底边更清晰，可选 */
:deep(.dlg-fixed-footer .el-dialog__header) {
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f2f5;
}

/* 主体区域占满剩余空间并可滚动 */
:deep(.dlg-fixed-footer .el-dialog__body) {
  flex: 1;
  overflow: auto; /* ★ 只有 body 滚动 */
  padding: 16px 24px; /* 你可以按需调整内边距 */
}

/* 页脚固定在底部，保持可见 */
:deep(.dlg-fixed-footer .el-dialog__footer) {
  position: sticky; /* 关键：粘在滚动容器底部 */
  bottom: 0;
  background: #fff;
  border-top: 1px solid #f0f2f5;
  padding: 12px 24px;
  z-index: 2; /* 盖住 body 内容的滚动 */
}

/* 细节：当内容很多时，底部加点阴影做层次感（可选） */
:deep(.dlg-fixed-footer .el-dialog__footer)::before {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  top: -8px;
  height: 8px;
  box-shadow: 0 -6px 12px rgba(0, 0, 0, 0.04);
  pointer-events: none;
}
</style>
